package com.mes.web.controller.hy;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.mes.entity.hy.Factory;
import com.mes.service.hy.IFactoryService;
import com.mes.utils.DateJsonValueProcessor;
import com.mes.utils.ExcelUtils;
import com.mes.utils.ResponseUtil;

/**
 * 
 * @ClassName:FactoryController
 * @Description: 工厂实现层controller
 * @Author hy
 * @Date 2018-5-30上午11:46:03
 * @version 1.0
 */
@Controller
@RequestMapping("/factory")
public class FactoryController {
	
	String limit1;
	String offset1;

	@Resource
	private IFactoryService iFactoryService;
	
	/**
	 * 查询所有
	 * @param response
	 * @param request
	 * @param limit	每页显示的行数
	 * @param offset	页码
	 * @param factory	工厂类
	 * @throws Exception
	 */
	@RequestMapping("/select")
	public void select(HttpServletResponse response,
			HttpServletRequest request,
			@RequestParam(value = "limit", required = false) String limit,
			@RequestParam(value = "offset", required = false) String offset,
			Factory factory) throws Exception {
		// 全局变量赋值，做当前页导出用
		limit1 = limit;
		offset1 = offset;
		if (!"".equals(offset)) {
			factory.setPage(Integer.parseInt(offset) / Integer.parseInt(limit));
		}
		factory.setPageSize(Integer.parseInt(limit));
		//转码
		if(!("").equals(factory.getFname()) && factory.getFname().equals(new String(factory.getFname()
				.getBytes("iso-8859-1"),"utf-8"))){
			factory.setFname(new String(factory.getFname().getBytes("iso-8859-1"),"utf-8"));
		}
		if(!("").equals(factory.getMproduct()) && factory.getMproduct().equals(new String(factory
				.getMproduct().getBytes("iso-8859-1"),"utf-8"))){
			factory.setMproduct(new String(factory.getMproduct().getBytes("iso-8859-1"),"utf-8"));
		}
		
		int total = iFactoryService.countByFactory(factory);
		List<Factory> factoryList = iFactoryService.selectByOther(factory);
		//判断是否为空白页
		if(factoryList.size() == 0){
			factory.setPage(factory.getPage() - 1);
			factoryList = iFactoryService.selectByOther(factory);
		}
		
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(factoryList, jsonConfig);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("total", total);
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * 主键查询
	 * @param fid 工厂主键id
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/selectByPrimaryKey")
	public void selectByPrimaryKey(Long fid, HttpServletResponse response)
			throws Exception {
		Factory select1 = iFactoryService.selectByPrimaryKey(fid);
		
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(select1, jsonConfig);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * 修改
	 * @param response
	 * @param factory 工厂类
	 * @throws Exception
	 */
	@RequestMapping("/update")
	public void update(HttpServletResponse response,Factory factory) throws Exception{
		/*修改成功*/
		String flag="1";
		iFactoryService.update(factory);
		ResponseUtil.write(response, flag);
	}
	
	/**
	 * 新增(工厂名称和主要产品不能与之前已存在的重复)
	 * @param response
	 * @param request
	 * @param factory 工厂类
	 * @throws Exception
	 */
	@RequestMapping("/insert")
	public void insert(HttpServletResponse response,
			HttpServletRequest request, Factory factory) throws Exception {
		/*添加成功*/
		String flag = "1";
		int count = (iFactoryService.selectByOther(factory)).size();
		if (count > 0) {
			/*此信息已存在*/
			flag = "2";
		} else {
			try {
				iFactoryService.insert(factory);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		ResponseUtil.write(response, flag);
	}

	/**
	 * 删除，可批量删除
	 * @param response
	 * @param fids 工厂id的字符串
	 * @throws Exception
	 */
	@RequestMapping("/delete")
	public void delete(HttpServletResponse response, String fids) throws Exception {
		int total = 0;
		String[] fid=fids.split(",");
		for(int i = 0;i < fid.length;i++){
			total += iFactoryService.deleteByPrimaryKey(Long.parseLong(fid[i]));
		}
		ResponseUtil.write(response, total);
	}

	/**
	 * 导出当前页
	 * @param response
	 * @param factory 工厂类
	 * @throws Exception
	 */
	@RequestMapping("/export")
	public void export(HttpServletResponse response, Factory factory)
			throws Exception {
		if (!"".equals(offset1)) {
			factory.setPage(Integer.parseInt(offset1) / Integer.parseInt(limit1));
		}
		factory.setPageSize(Integer.parseInt(limit1));
		
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("当前页工厂信息");
		HSSFRow row = sheet.createRow((int) 0);
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("序号");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("工厂名称");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("建立时间");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("地址");
		cell.setCellStyle(style);
		cell = row.createCell(4);
		cell.setCellValue("主要产品");
		cell.setCellStyle(style);
		cell = row.createCell(5);
		cell.setCellValue("生产能力");
		cell.setCellStyle(style);
		cell = row.createCell(6);
		cell.setCellValue("工厂负责人");
		cell.setCellStyle(style);
		cell = row.createCell(7);
		cell.setCellValue("联系电话");
		cell.setCellStyle(style);
		// 导出当前页
		List<Factory> list = iFactoryService.selectByOther(factory);
		for (int i = 0; i < list.size(); i++) {
			row = sheet.createRow((int) i + 1);
			Factory factory2 = list.get(i);
			row.createCell(0).setCellValue(i + 1);
			row.createCell(1).setCellValue(factory2.getFname());
			row.createCell(2).setCellValue(factory2.getDate());
			row.createCell(3).setCellValue(factory2.getAddress());
			row.createCell(4).setCellValue(factory2.getMproduct());
			row.createCell(5).setCellValue(factory2.getPcapacity());
			row.createCell(6).setCellValue(factory2.getPmanager());
			row.createCell(7).setCellValue(factory2.getPhone());
		}
		Date now = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String nowtime = sdf.format(now);
		String fileName = nowtime + "工厂信息表.xls";
		fileName = new String(fileName.getBytes("GBK"), "iso8859-1");
		try {
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename="
					+ fileName);
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			OutputStream output = response.getOutputStream();
			BufferedOutputStream bufferedOutPut = new BufferedOutputStream(
					output);
			bufferedOutPut.flush();
			wb.write(bufferedOutPut);
			bufferedOutPut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 导出所有
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/exportAll")
	public void exportAll(HttpServletResponse response) throws Exception {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("所有工厂信息");
		HSSFRow row = sheet.createRow((int) 0);
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("工厂名称");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("建立时间");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("地址");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("法定代表人");
		cell.setCellStyle(style);
		cell = row.createCell(4);
		cell.setCellValue("工厂负责人");
		cell.setCellStyle(style);
		cell = row.createCell(5);
		cell.setCellValue("联系电话");
		cell.setCellStyle(style);
		cell = row.createCell(6);
		cell.setCellValue("传真");
		cell.setCellStyle(style);
		cell = row.createCell(7);
		cell.setCellValue("办公室人数");
		cell.setCellStyle(style);
		cell = row.createCell(8);
		cell.setCellValue("工人人数");
		cell.setCellStyle(style);
		cell = row.createCell(9);
		cell.setCellValue("建筑总面积");
		cell.setCellStyle(style);
		cell = row.createCell(10);
		cell.setCellValue("主要产品");
		cell.setCellStyle(style);
		cell = row.createCell(11);
		cell.setCellValue("生产能力");
		cell.setCellStyle(style);
		cell = row.createCell(12);
		cell.setCellValue("描述");
		cell.setCellStyle(style);
		List<Factory> list = iFactoryService.selectAll();
		for (int i = 0; i < list.size(); i++) {
			row = sheet.createRow((int) i + 1);
			Factory factory2 = list.get(i);
			row.createCell(0).setCellValue(factory2.getFname());
			row.createCell(1).setCellValue(factory2.getDate());
			row.createCell(2).setCellValue(factory2.getAddress());
			row.createCell(3).setCellValue(factory2.getRepresentative());
			row.createCell(4).setCellValue(factory2.getPmanager());
			row.createCell(5).setCellValue(factory2.getPhone());
			row.createCell(6).setCellValue(factory2.getFax());
			row.createCell(7).setCellValue(factory2.getOnum());
			row.createCell(8).setCellValue(factory2.getFnum());
			row.createCell(9).setCellValue(factory2.getArea());
			row.createCell(10).setCellValue(factory2.getMproduct());
			row.createCell(11).setCellValue(factory2.getPcapacity());
			row.createCell(12).setCellValue(factory2.getDescription());
		}
		Date now = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String nowtime = sdf.format(now);
		String fileName = nowtime + "工厂信息表.xls";
		fileName = new String(fileName.getBytes("GBK"), "iso8859-1");
		try {
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename="
					+ fileName);
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			OutputStream output = response.getOutputStream();
			BufferedOutputStream bufferedOutPut = new BufferedOutputStream(
					output);
			bufferedOutPut.flush();
			wb.write(bufferedOutPut);
			bufferedOutPut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 导入
	 * @param file 导入文件
	 * @param request
	 * @param response
	 * @throws URISyntaxException
	 * @throws IOException
	 */
	@RequestMapping("/uplodeFile")
	public void importor(@RequestParam("file") CommonsMultipartFile file,
			HttpServletRequest request, HttpServletResponse response)
			throws URISyntaxException, IOException {
		String savePath = ((HttpSession) request).getServletContext().getRealPath(
				"/WEB-INF/" + file.getOriginalFilename());
		File newFile = new File(savePath);
		// 通过CommonsMultipartFile的方法直接写文件（注意这个时候）
		file.transferTo(newFile);
		// 取文件后缀
		String subfix = savePath.lastIndexOf(".") == -1 ? "" : savePath
				.substring(savePath.lastIndexOf(".") + 1);
		List<List<String>> lists = new ArrayList<>();
		// 获取导入行数
		List<String> names = names();
		int num = names.size();
		String str = "xls";
		String strx = "xlsx";
		if (subfix.equals(str)) {
			lists = ExcelUtils.readXls(savePath, request, num+1);
		} else if (subfix.equals(strx)) {
			lists = ExcelUtils.readXlsx(savePath, request, num+1);
		} else {
			response.getWriter().print("0");
		}
		int count = 0;
		int flag = 1;
		for (int i = 0; i < lists.size(); i++) {
			List<String> list = new ArrayList<>();
			list = lists.get(i);
			Factory factory = new Factory();
			factory.setFname(list.get(0) == null ? "" : list.get(0));
			factory.setDate(list.get(1) == null ? "" : list.get(1));
			factory.setAddress(list.get(2) == null ? "" : list.get(2));
			factory.setRepresentative(list.get(3) == null ? "" : list.get(3));
			factory.setPmanager(list.get(4) == null ? "" : list.get(4));
			factory.setPhone(list.get(5) == null ? "" : list.get(5));
			factory.setFax(list.get(6) == null ? "" : list.get(6));
			factory.setOnum(list.get(7) == null ? "" : list.get(7));
			factory.setFnum(list.get(8) == null ? "" : list.get(8));
			factory.setArea(list.get(9) == null ? "" : list.get(9));
			factory.setMproduct(list.get(10) == null ? "" : list.get(10));
			factory.setPcapacity(list.get(11) == null ? "" : list.get(11));
			factory.setDescription(list.get(12) == null ? "" : list.get(12));
			//根据名字和主要产品查询是否已存在，如果存在直接跳过
			int ff = iFactoryService.sel(factory);
			if(ff == 0){
				// 添加功能
				iFactoryService.insert(factory);
				count++;
			}	
		}
		if (count == 0) {
			flag = 0;
		}
		response.getWriter().print(flag);
	}

	/**
	 * 导入模板表头
	 * @return
	 */
	public List<String> names() {
		List<String> list = new ArrayList<>();
		list.add("工厂名称");
		list.add("建立日期");
		list.add("地址");
		list.add("法定代表人");
		list.add("工厂负责人");
		list.add("联系电话");
		list.add("传真");
		list.add("办公室人数");
		list.add("工人人数");
		list.add("建筑总面积");
		list.add("主要产品");
		list.add("生产能力");
		list.add("描述");
		return list;
	}
	/**
	 * 导出模板
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/doExportFile")
	public void doExportFile(HttpServletRequest request,HttpServletResponse response) throws Exception{
		ExcelUtils.exportFile("工厂信息导入模板",names(), response);
	}
}
